package mc.support.orm.handler;

import com.alibaba.fastjson.JSON;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA. <br/>
 * Author: Francis Yun    <br/>
 * Date: 2013-12-18  <br/>
 */
public abstract class JsonMappingTypeHandler<T> implements TypeHandler<T> {

    private final Class<T> clazz;

    public JsonMappingTypeHandler(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        String json = null != parameter ? JSON.toJSONString(parameter) : null;
        ps.setString( i, json );
    }

    @Override
    public T getResult(ResultSet rs, String columnName) throws SQLException {
        String json = rs.getString( columnName );
        return null != json ? JSON.parseObject( json, clazz ) : null;
    }

    @Override
    public T getResult(ResultSet rs, int columnIndex) throws SQLException {
        String json = rs.getString( columnIndex );
        return null != json ? JSON.parseObject( json, clazz ) : null;
    }

    @Override
    public T getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String json = cs.getString( columnIndex );
        return null != json ? JSON.parseObject( json, clazz ) : null;
    }

}
